package de.roskenet.clou.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import org.apache.commons.dbcp.BasicDataSource;

import de.roskenet.clou.model.ClouDay;

public class ClouDayDAO {
	
	private BasicDataSource dataSource;
	
	public BasicDataSource getDataSource() {
		return dataSource;
	}

	public void setDataSource(BasicDataSource dataSource) {
		this.dataSource = dataSource;
	}

	public ClouDay getByDay(int day) {
		ClouDay retVal = new ClouDay();
		
		String SQL = "SELECT * FROM clouday WHERE tag=? ORDER BY (id) DESC";
		try {
			Connection conn = dataSource.getConnection();
			PreparedStatement stmt = conn.prepareStatement(SQL);
			stmt.setInt(1, day);
		
			ResultSet rs = stmt.executeQuery();
		
			if(rs.next()) {
				// retVal = new ClouDay();
				retVal.setId(rs.getLong("id"));
				retVal.setTag(rs.getInt("tag"));
				retVal.setTitle(rs.getString("title"));
				retVal.setDescr(rs.getString("descr"));
			}
			
			rs.close();
			stmt.close();
			conn.close();
			
		} catch (SQLException sqle) {
			System.out.println("Something went wrong in getByDay!");
		}
		
		return retVal;
	}
	
	public boolean saveOrUpdate(ClouDay clouDay) {
		boolean retVal = true;
		
		String SQL = null;
		
		if(clouDay.getId() == 0) {
			SQL = "INSERT INTO clouday (tag, title, descr, picsmall, picbig) VALUES (?,?,?,?,?) RETURNING id";
		}
		else {
			SQL = "UPDATE clouday SET tag=?, title=?, descr=?, picsmall=?, picbig=? WHERE id=\'" +
					clouDay.getId() + "\' RETURNING id";
		}
		
		try {
			Connection conn = dataSource.getConnection();
			PreparedStatement stmt = conn.prepareStatement(SQL);
			stmt.setInt(1, clouDay.getTag());
			stmt.setString(2, clouDay.getTitle());
			stmt.setString(3, clouDay.getDescr());
			stmt.setString(4, clouDay.getPicsmall());
			stmt.setString(5, clouDay.getPicbig());
		
			ResultSet rs = stmt.executeQuery();
			
			if(rs.next()) {
				clouDay.setId(rs.getLong("id"));
				System.out.println("Der Datensatz hat die id: " + clouDay.getId());
			}
			
			rs.close();
			stmt.close();
			conn.close();
			
		} catch (SQLException sqle) {
			
		}
		
		return retVal;
	}
}
